package com.ysu.zyw.cs;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by ZeRur on 2016/1/13.
 *
 * @author yaowu.zhang
 */
public class ArticleDao {

    private static final Map<String, Article> db = new HashMap<>();

    {
        // init data
        for (int i = 0; i < 30; i++) {
            db.put(String.valueOf(i), new Article(String.valueOf(i), "article - " + i));
        }
    }

    /**
     * 使用 default / backup Cache 做缓存, key 为参数 articleId, 条件为参数 article.id < 15
     * @param article
     */
    @CachePut(cacheManager = "cacheManager", cacheNames = {"default", "backup"}, key = "#article.id", condition = "T(java.lang.Integer).parseInt(#article.id) < 15")
    public Article insert(Article article) {
        System.out.println("db - insert - " + article.getId());
        db.put(article.getId(), article);
        return article;
    }

    @CacheEvict(cacheManager = "cacheManager", cacheNames = {"default", "backup"}, key = "#articleId")
    public void delete(String articleId) {
        System.out.println("db - delete - " + articleId);
        db.remove(articleId);
    }

    @CachePut(cacheManager = "cacheManager", cacheNames = {"default", "backup"}, key = "#article.id", condition = "T(java.lang.Integer).parseInt(#article.id) < 15")
    public Article update(Article article) {
        System.out.println("db - update - " + article.getId());
        db.put(article.getId(), article);
        return article;
    }

    /**
     * 使用 default / backup Cache 做缓存, key 为参数 articleId, 条件为参数 articleId < 15, 除去结果 id = 10
     */
    @Cacheable(cacheManager = "cacheManager", cacheNames = {"default", "backup"}, key = "#articleId", condition = "T(java.lang.Integer).parseInt(#articleId) < 15", unless = "#result != null and #result.id.equals('10')")
    public Article select(String articleId) {
        System.out.println("db - select - " + articleId);
        return db.get(articleId);
    }

}
